//
//  ARKeyboardInputController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/18.
//

import UIKit
import SnapKit
import IQKeyboardManagerSwift

struct ARKeyboardInputConfig {
    
    var placeholder: String = ARHelper.localString("Enter your ideas...")
    var sendBtnText: String = ARHelper.localString("Done")
    var defaultText: String = ""
    
}

class ARKeyboardInputController: ARBaseViewController {

    private let config: ARKeyboardInputConfig
    private var viewWillAppear: Bool = false
    
    private let sendCallback: (_ str: String) -> Void
    private var dismissCallback: (() -> Void)?
    
    // MARK: - Init
    
    class func showKeyboardInput(at controller: UIViewController,
                                 config: ARKeyboardInputConfig = ARKeyboardInputConfig(),
                                 send: @escaping (_ str: String) -> Void,
                                 dismiss: (() -> Void)? = nil)
    {
        let vc = ARKeyboardInputController(config: config, send: send)
        vc.dismissCallback = dismiss
        controller.present(vc, animated: false)
    }
    
    private init(config: ARKeyboardInputConfig, send: @escaping (_ str: String) -> Void) {
        self.config = config
        self.sendCallback = send
        super.init(nibName: nil, bundle: nil)
        
        self.modalTransitionStyle = .crossDissolve
        self.modalPresentationStyle = .overCurrentContext
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        IQKeyboardManager.shared.enable = true
        
        if !viewWillAppear {
            viewWillAppear = true
            
            DispatchQueue.main.async {
                UIView.animate(withDuration: 0.3) { [weak self] in
                    self?.bgBtn.alpha = 1.0
                }
                self.textField.becomeFirstResponder()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        IQKeyboardManager.shared.enable = false
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        self.view.backgroundColor = .clear
        self.view.addSubview(bgBtn)
        self.view.addSubview(containerView)
        
        bgBtn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }
        
        // 设置值
        sendBtn.setTitle(config.sendBtnText, for: .normal)
        textField.placeholder = config.placeholder
        if config.defaultText.isEmpty == false {
            textField.text = config.defaultText
        }
    }
    

    // MARK: - Action
    
    @objc private func bgBtnClicked(_ sender: UIButton) {
        textField.endEditing(true)
        UIView.animate(withDuration: 0.3) {
            sender.alpha = 0.0
        } completion: { [weak self] flag in
            self?.dismiss(animated: false)
            self?.dismissCallback?()
        }
    }
    
    @objc private func sendBtnClicked(_ sender: UIButton) {
        sendCallback(textField.text ?? "")
        bgBtnClicked(bgBtn)
    }
    
    // MARK: - Lazy
    
    private lazy var bgBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(bgBtnClicked(_:)), for: .touchUpInside)
        btn.backgroundColor = .black.withAlphaComponent(0.5)
        btn.alpha = 0.0
        return btn
    }()
    
    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(hexString: "#FAFAFA")
        
        let sendBtnShadowsView = UIView()
        sendBtnShadowsView.backgroundColor = .white
        sendBtnShadowsView.layer.cornerRadius = 16
        sendBtnShadowsView.layer.shadowColor = (UIColor(hexString: "#60CFFF") ?? .black).cgColor
        sendBtnShadowsView.layer.shadowOpacity = 0.4
        sendBtnShadowsView.layer.shadowOffset = CGSize(width: 3, height: 3)
        
        view.addSubview(textInputView)
        view.addSubview(sendBtnShadowsView)
        view.addSubview(sendBtn)
        
        sendBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.width.equalTo(64)
            make.height.equalTo(32)
            make.centerY.equalTo(textInputView)
        }
        
        sendBtnShadowsView.snp.makeConstraints { make in
            make.edges.equalTo(sendBtn)
        }
        
        textInputView.snp.makeConstraints { make in
            make.height.equalTo(36)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.right.equalTo(sendBtn)
            make.left.equalToSuperview().offset(20)
        }
        
        return view
    }()
    
    private lazy var textInputView: UIView = {
        let view = UIView()
        
        view.layer.cornerRadius = 18
        view.backgroundColor = UIColor(hexString: "#F2F2F2")
        
        view.addSubview(textField)
        
        textField.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
        }
        
        return view
    }()
    
    private lazy var textField: UITextField = {
        let textField = UITextField()
//        textField.delegate = self
        textField.font = ARHelper.font(12, weight: .regular)
        return textField
    }()
    
    private lazy var sendBtn: UIButton = {
        let btn = UIButton.ar.themeStyleButton(height: 32)
        btn.addTarget(self, action: #selector(sendBtnClicked(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Done"), for: .normal)
        return btn
    }()

}
